#!/usr/bin/env bash

# easy to change directory #
alias d='dirs -v'
alias dsk='init_dirstack'
function init_dirstack() {
  local oldpwd=${OLDPWD-$(pwd)} _dirstack _d
  dirs -c
  _dirstack="$(cat ${snippets_dir}/.ignore_files/dirstack 2>/dev/null)"
  if [[ -n $_dirstack ]]; then
    for _d in $(echo "$_dirstack" | xargs -n1 | tac); do
      pushd $_d &>/dev/null
    done
    popd -0 &>/dev/null
  fi
  export OLDPWD=$oldpwd
}
function convert_root_realpath() {
  echo "$*" | sed -E "s@(^\s*|\s+)~@\1$(realpath ~)@g"
}
function pj() {
  local _num _dir
  if [[ $1 =~ ^[0-9]+$ ]]; then
    _dir="$(dirs -v | grep "^\s$1 " | awk '{print $2}')"
  elif [[ -z $1 ]]; then
    _dir=-
  else
    _dir="$(single_select "$(dirs -v | awk '{print $2}' | grep -i "$1" | grep -v "^$(pwd)$")")"
  fi
  if [[ -n $_dir ]]; then
    eval "cd $_dir"
  fi
}
function pu() {
  local _num _dir
  if [[ $1 =~ ^[0-9]+$ ]]; then
    _num=$1
  elif [[ -z $1 ]]; then
    :
  else
    if [[ $1 = "-" ]];then
      _num=$OLDPWD
    elif ! [[ -e $1 ]]; then
      _dir="$(single_select "$(dirs -v | awk '{print $2}' | grep -i "$1" | grep -v "^$(pwd)$")")"
      _num="$(dirs -v | awk -v dir=$_dir '{ if($2==dir){print $1}; close(cmd);}')"
    else
      _num=$1
    fi
  fi
  init_dirstack # reset
  if [[ $_num ]]; then
    _num="$(echo $_num | sed -E 's/^[0-9]+$/+&/g')"
    pushd ${_num-$1} &>/dev/null
  elif [[ $# -eq 0 ]]; then
    pushd &>/dev/null
  fi
  pwd
  sets .ignore_files/dirstack "$(convert_root_realpath ${DIRSTACK[@]})"
  unset _whoami
}
function pd() {
  _whoami=$(whoami)
  cd "$*"
  sets .ignore_files/dirstack $(convert_root_realpath ${DIRSTACK[@]})
  d
  unset _whoami
}
function po() {
  _whoami=$(whoami)
  popd $(echo $* | sed -E 's/[0-9]+/+&/g') &>/dev/null
  sets .ignore_files/dirstack $(convert_root_realpath ${DIRSTACK[@]})
  d
  unset _whoami
}
# init_dirstack

